package com.polaris.live.viewmodel.login

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.polaris.live.common.AppModule
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.common.resp.UserResp
import com.polaris.live.manager.AppConfigManager
import com.polaris.live.manager.DomainManager
import com.polaris.live.net.userService
import com.polaris.live.resp.go_resp.LoginPhoneBean
import com.polaris.live.utils.SetMapData
import kotlinx.coroutines.launch

/**
 * LoginViewModel
 *
 * @author Created by 半仙 on 2023/9/16/016 16:51
 */
open class LoginViewModel : BaseViewModel() {

    //登录预检测
    val gotoLoginLiveData = MutableLiveData<Int>()
    fun gotoLogin(type: Int) {
        val postResp = AppConfigManager.getConfigPost()
        if (postResp != null) {
            gotoLoginLiveData.postValue(type)
        } else {
            //如果为空需要重新获取一下
            request({ userService.configPost(SetMapData.genPostMap()) }, {
                AppConfigManager.updateConfigPost(it)

                gotoLoginLiveData.postValue(type)
            })
        }
    }

    //获取ip
    val ipLiveData = MutableLiveData<String?>()
    fun getIp() {
        viewModelScope.launch {
            DomainManager.fetchIpCountry().also {
                ipLiveData.value = it
            }
        }
    }

    //google登录
    val googleLoginLiveData = MutableLiveData<ResultState<UserResp>>()
    fun googleLogin(id: String, token: String) {
        val loginPhoneBean = LoginPhoneBean(
            apiId = id,
            apiToken = token,
            appLanguage = AppModule.getLanguageAndArea()
        )

        request({ userService.loginGoogle(loginPhoneBean) }, googleLoginLiveData)
    }

    //设备登录
    val deviceLoginLiveData = MutableLiveData<ResultState<UserResp>>()
    fun deviceLogin() {
        val loginPhoneBean = LoginPhoneBean(appLanguage = AppModule.getLanguageAndArea())

        request({ userService.loginDevice(loginPhoneBean) }, deviceLoginLiveData)
    }

    companion object {

        const val GOTO_PHONE = 0
        const val GOTO_GOOGLE = 1
        const val GOTO_GMAIL = 3
        const val GOTO_DEVICE = 4
    }
}